package com.litchi.tutor.controller;

import com.litchi.tutor.common.base.ResponseVO;
import com.litchi.tutor.common.entity.TeacherPerformanceImages;
import com.litchi.tutor.config.Properties;
import com.litchi.tutor.mapper.TeacherPerformanceImagesMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * @author xyouzi
 * @date 2021/10/30 21:56
 */
@RestController
@RequestMapping("/upload")
@Api("文件上传")
public class FileController {

    @Autowired
    TeacherPerformanceImagesMapper teacherPerformanceImagesMapper;

    /**
     * 图片上传
     * @param file
     * @return
     */
    @ApiOperation("单文件上传")
    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    public ResponseVO fileUpload(@RequestParam(value = "file") MultipartFile file) throws ParseException {
        String fileName = upload(file);
        return ResponseVO.ok(fileName);
    }

    /**
     * 批量上传
     * @param files
     * @return
     */
    @ApiOperation("多文件上传")
    @RequestMapping(value = "/batchUpload", method = RequestMethod.POST)
    public ResponseVO fileUpload(@RequestParam(value = "files") MultipartFile[] files) throws ParseException {
        List<String> list = new ArrayList<>();
        for (MultipartFile file : files) {
            String fileName = upload(file);
            TeacherPerformanceImages teacherPerformanceImages = new TeacherPerformanceImages();
            teacherPerformanceImages.setImageUrl(fileName);
            teacherPerformanceImagesMapper.insert(teacherPerformanceImages);
            list.add(fileName);
        }
        return ResponseVO.ok(list);
    }

    /**
     * 上传公共方法
     * @param file
     * @return
     */
    private String upload(@RequestParam("file") MultipartFile file) throws ParseException {
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = Properties.IMAGES_URL_PRE;

        int i = (int) ((Math.random() * 9 + 1) * 100000);
        long time = new Timestamp(System.currentTimeMillis()).getTime();
        String randomNum = new StringBuilder().append(i).append("-").append(time).toString();

        // 按照日期放文件文件夹
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM");
        Date date=getMonthDate(sdf.parse(sdf.format(new Date())),1);
        String format = sdf.format(date);


        fileName = "/upload/" + format + "/" + randomNum + suffixName; // 新文件名

        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    public static Date getMonthDate(Date startDate,int month){
        LocalDateTime localDateTime = startDate.toInstant()
                .atZone(ZoneId.systemDefault() )
                .toLocalDateTime().plusMonths(month);
        Date date = Date.from(localDateTime.atZone( ZoneId.systemDefault()).toInstant());
        return date;
    }

}
